<template>
  <div class="model-manage">
    <!-- 搜索框 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-input
            v-model="searchQuery"
            placeholder="请输入模型名称或内容"
            prefix-icon="el-icon-search"
            @keyup.enter.native="fetchData"
        ></el-input>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="fetchData" style="margin-bottom: 20px;">搜索</el-button>
        <el-button @click="resetData" style="margin-bottom: 20px;">重置</el-button>
        <el-button type="success" @click="openDialog('add')" style="margin-bottom: 20px;">添加模型</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        :header-cell-style="{ background: '#ccc' }"
        border
    >
      <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="avatar"
          label="头像"
          align="center"
      >
        <template slot-scope="scope">
          <!--<img :src="scope.row.avatar" alt="" style="width: 50px; height: 50px;">-->
          <el-image :preview-src-list="[scope.row.avatar]" style="width: 50px; height: 50px" :src="scope.row.avatar"
                    fit="cover"></el-image>
        </template>
      </el-table-column>
      <el-table-column
          prop="name"
          label="模型名称"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="content"
          label="模型详细内容"
          align="center"
      >
        <template slot-scope="scope">
          <el-button size="mini" @click="openDrawer(scope.row)" type="primary" style="margin-left: 16px;">
            详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
          prop="current"
          label="创建时间"
          align="center"
          width="180"
      ></el-table-column>
      <el-table-column
          label="操作"
          width="180"
          align="center"
          fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="info" size="mini" @click="openDialog('edit', scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="deleteModel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
        title="模型详情"
        :visible.sync="drawer"
        size="40%"
        direction="rtl">
      <v-md-editor v-model="drawerContent" mode="preview" height="auto"></v-md-editor>
    </el-drawer>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>

    <!-- 添加/编辑模型的弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-form :model="modelForm" ref="modelForm" label-width="120px" style="padding-right: 100px;">
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              :action="$baseUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="modelForm.avatar" :src="modelForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="模型名称" prop="name" :rules="[{ required: true, message: '模型名称不能为空' }]">
          <el-input v-model="modelForm.name" placeholder="请输入模型名称"></el-input>
        </el-form-item>
        <el-form-item label="模型内容" prop="content" :rules="[{ required: true, message: '模型内容不能为空' }]">
          <!--<el-input v-model="modelForm.content" placeholder="请输入模型内容"></el-input>-->
          <!--<v-md-editor v-model="modelForm.content" mode="edit" height="500px"></v-md-editor>-->
          <v-md-editor
              mode="edit"
              v-model="modelForm.content"
              left-toolbar="undo redo h bold italic strikethrough quote ul ol table hr link code | image"
              right-toolbar="preview toc sync-scroll fullscreen"
              :disabled-menus="[]"
              @upload-image="handleUploadImage"
              height="500px"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveModel">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from "@/api";
import {formatDate} from "@/utils/date";

export default {
  name: "ModelManage",
  data() {
    return {
      searchQuery: "", // 搜索关键词
      tableData: [], // 表格数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 总条数
      dialogVisible: false, // 弹出框是否显示
      dialogTitle: "", // 弹出框标题
      modelForm: {
        id: null,
        name: "",
        content: "",
        avatar: "",
        current: ""
      }, // 模型表单数据
      currentAction: "", // 当前操作类型（add/edit）
      drawer: false,
      drawerContent: '',
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      console.log(event);
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        api.file.upload(file).then(r => {
          insertImage({url: r.data.message});
        })
      }
    },
    openDrawer(val) {
      this.drawer = true;
      this.drawerContent = val.content;
    },
    resetData() {
      this.searchQuery = '';
      this.fetchData();
    },
    // 获取数据
    async fetchData() {
      // 模拟从后端获取数据
      const response = await api.model.modelList();
      const mockData = response.data.data;
      // 根据搜索关键词过滤数据
      let filteredData = mockData.filter((item) =>
          item.name.includes(this.searchQuery) || item.content.includes(this.searchQuery)
      );

      // 分页处理
      this.total = filteredData.length;
      this.tableData = filteredData.slice(
          (this.currentPage - 1) * this.pageSize,
          this.currentPage * this.pageSize
      );
    },
    // 每页显示条数改变时触发
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    // 当前页码改变时触发
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    // 打开弹出框
    openDialog(action, row = null) {
      this.currentAction = action;
      if (action === "add") {
        this.dialogTitle = "添加模型";
        this.modelForm = {
          id: null,
          name: "",
          content: "",
          avatar: "",
          current: ""
        };
      } else if (action === "edit") {
        this.dialogTitle = "编辑模型";
        this.modelForm = {...row};
      }
      this.dialogVisible = true;
    },
    // 保存模型
    saveModel() {
      this.$refs.modelForm.validate((valid) => {
        if (valid) {
          this.modelForm.current = formatDate(this.modelForm.current);
          if (this.currentAction === "add") {
            // 添加模型逻辑
            api.model.modelAppend(this.modelForm).then(r => {
              if (r.data.code === 200) {
                this.fetchData();
                this.$message.success('添加成功');
              }
            });
          } else if (this.currentAction === "edit") {
            // 编辑模型逻辑
            api.model.modelEditor(this.modelForm).then(r => {
              if (r.data.code === 200) {
                this.fetchData();
                this.$message.success('编辑成功');
              }
            });
          }
          this.dialogVisible = false;
        }
      });
    },
    // 删除模型
    deleteModel(row) {
      this.$confirm("确定要删除该模型吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除模型逻辑
        api.model.modelDelete(row.id).then(r => {
          if (r.data.code === 200) {
            this.$message.success('删除成功！');
            this.fetchData();
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 头像上传成功回调
    handleAvatarSuccess(res, file) {
      console.log(file);
      this.modelForm.avatar = res.message; // 假设后端返回的图片地址在 res.message 中
    },
    // 头像上传前校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style scoped>
.model-manage {
  padding: 20px;
}
</style>